package xhwl.hmo.mall.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.List;

import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.adapter.CommentListAdapter;
import xhwl.hmo.mall.adapter.SuitPagerAdapter;
import xhwl.hmo.mall.adapter.SuitProductsAdapter;
import xhwl.hmo.mall.bean.GoodType;
import xhwl.hmo.mall.http.api.GetGoodsDetailApi;
import xhwl.hmo.mall.http.api.ProductsCommentApi;
import xhwl.hmo.mall.http.bean.resp.CommentListResp;
import xhwl.hmo.mall.http.bean.resp.GoodsDetailResp;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.utils.XHLog;
import xhwl.hmo.mall.views.GridViewforScrollView;
import xhwl.hmo.mall.views.MyScrollViews;
import xhwl.hmo.mall.views.NewWebView;
import xhwl.hmo.mall.views.PullUpToLoadMore;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


/**
 * 产品详情页 卡和套餐
 */
public class SuiteProductsDetailActivity extends BaseActivity implements View.OnClickListener {
    private ViewPager viewpager;
    private TextView name_card;
    private TextView summary_card;
    private TextView sum_pay;
    private TextView price_original;
    private TextView sum_saled;
    private TextView sum_comment;
    private RelativeLayout comment_layout;
    private RecyclerView mRecyclerView;
    private TextView comment_check;
    private TextView tuwen_detail;
    private TextView sum_pay_bottom;
    private TextView price_original_bottom;
    private TextView buy_now;
    public String good_id = "";
    SuitProductsAdapter adapterSuits;
    List<GoodsDetailResp.SuitsProducts> suitsProductslist = new ArrayList<>();//套装内容
    List<CommentListResp.COMMENTLISTBean> mList = new ArrayList<>();
    CommentListAdapter adapter;
    public static final String EXTRA_POSITION = "position";//用于精品推荐页面传递position实现点击哪一页面时图片正好显示哪一张图片
    public static final String EXTRA_FROM = "from";//主要是用来判断从哪个页面跳转来到这个页面的,这个地方主要就是判断是不是从精品推荐过来的
    int position;//精品推荐滑动页面当前处于第几张图片的position
    int from;
    //页面顶部viewpager和小圆点的处理
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
                pagercirculation();
            }
        }
    };
    private RadioGroup pager_radiogroup;
    //---------------------------------------webview的
    String ur = "http://hmall.yk2020.com/app/ginfo/gid/";
    String shareurl = "http://hmall.yk2020.com/index.php?m=Member&c=app&a=share&gid=";
    private NewWebView webview;
    private GridViewforScrollView gridview;
    private PullUpToLoadMore ptlm;
    private RelativeLayout title_layout_first;
    private LinearLayout suit_content_layout;
    GoodsDetailResp data;
    private LinearLayout back_layout;
    private ImageView right_imageview;
    private MyScrollViews myscrolview_bottom;
    private RelativeLayout title_llayout;
    private LinearLayout title_llBack;
    private ImageView title_img;
    private RelativeLayout rl_tag;
    private TextView text1, text2, text3;
    private RelativeLayout layout_price_bottom;
    private RelativeLayout layout_price;

    //--------------webview的
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        good_id = getIntent().getStringExtra("GOOD_ID");
        from = getIntent().getIntExtra(EXTRA_FROM, 0);//判断该页面从哪传过来 1,从精品推荐过来
        position = getIntent().getIntExtra(EXTRA_POSITION, 0);
        setContentView(R.layout.activity_suite_products_detail);
    }

    @Override
    protected void processOper() {
        super.processOper();
        adapterSuits = new SuitProductsAdapter(this, suitsProductslist);//套装内容
        gridview.setAdapter(adapterSuits);
        initRecylerView();
        adapter = new CommentListAdapter(this, mList);//评价内容
        mRecyclerView.setAdapter(adapter);

    }

    @Override
    public void initViews() {
        title_llayout = (RelativeLayout) findViewById(R.id.title_llayout);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        gridview = (GridViewforScrollView) findViewById(R.id.gridview);
        pager_radiogroup = (RadioGroup) findViewById(R.id.pager_radiogroup);
        name_card = (TextView) findViewById(R.id.name_card);
        summary_card = (TextView) findViewById(R.id.summary_card);
        sum_pay = (TextView) findViewById(R.id.sum_pay);
        price_original = (TextView) findViewById(R.id.price_original);
        sum_saled = (TextView) findViewById(R.id.sum_saled);
        sum_comment = (TextView) findViewById(R.id.sum_comment);
        comment_layout = (RelativeLayout) findViewById(R.id.comment_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        comment_check = (TextView) findViewById(R.id.comment_check);
        tuwen_detail = (TextView) findViewById(R.id.tuwen_detail);
        sum_pay_bottom = (TextView) findViewById(R.id.sum_pay_bottom);
        price_original_bottom = (TextView) findViewById(R.id.price_original_bottom);
        buy_now = (TextView) findViewById(R.id.buy_now);
        ptlm = (PullUpToLoadMore) findViewById(R.id.ptlm);
        title_layout_first = (RelativeLayout) findViewById(R.id.title_layout_first);
        layout_price_bottom = (RelativeLayout) findViewById(R.id.layout_price_bottom);
        layout_price = (RelativeLayout) findViewById(R.id.layout_price);
        suit_content_layout = (LinearLayout) findViewById(R.id.suit_content_layout);
        back_layout = (LinearLayout) findViewById(R.id.back_layout);
        title_llBack = (LinearLayout) findViewById(R.id.title_llBack);
        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        text3 = (TextView) findViewById(R.id.text3);
        title_img = (ImageView) findViewById(R.id.title_img);
        right_imageview = (ImageView) findViewById(R.id.right_imageview);
        rl_tag = (RelativeLayout) findViewById(R.id.rl_tag);
        initwebview();
    }

    //商品详情页面数据处理
    private void setData(GoodsDetailResp data) {
        if (null != data.getGOODS_NAME()) {
            name_card.setText(data.getGOODS_NAME());
        }
        if (null != data.getGOODS_DESC()) {
            summary_card.setText(data.getGOODS_DESC());
        }
        if (null != data.getGOODS_MONEY()) {
            if (data.getGOODS_MONEY().equals(data.getGOODS_SALE_MONEY())) {
                layout_price.setVisibility(View.GONE);
                layout_price_bottom.setVisibility(View.GONE);
            } else {
                price_original.setText("￥" + data.getGOODS_MONEY());
                price_original_bottom.setText("￥" + data.getGOODS_MONEY());
                layout_price.setVisibility(View.VISIBLE);
                layout_price_bottom.setVisibility(View.VISIBLE);
            }
        }
        if (null != data.getGOODS_SALE_MONEY()) {
            sum_pay.setText("￥" + data.getGOODS_SALE_MONEY());
            sum_pay_bottom.setText("￥" + data.getGOODS_SALE_MONEY());
        }
        if (null != data.getNUM()) {
            sum_saled.setText("已售" + data.getNUM() + "件");
        }
        if (!StringUtil.isEmpty(data.getSERVER_APP())) {
            final String[] server_app = data.getSERVER_APP().split(";");
            if (server_app.length > 0) {
                text1.setText(null != server_app[0] ? server_app[0] : "");
                text2.setText(null != server_app[1] ? server_app[1] : "");
                text3.setText(null != server_app[2] ? server_app[2] : "");
            }
        }
        dealTopViewPager(data);
        //套餐包含项目展示
        if (data.getDEV_INFO() != null && data.getDEV_INFO().size() != 0) {
            suitsProductslist.addAll(data.getDEV_INFO());
            adapterSuits.notifyDataSetChanged();
        }
    }

    //底部滑动页面webview的设置
    private void initwebview() {
        webview = (NewWebView) findViewById(R.id.webview);
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getParent().requestDisallowInterceptTouchEvent(false);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        //设置此属性，可任意比例缩放
        webview.getSettings().setUseWideViewPort(false);
        // 设置不出现缩放工具
        webview.getSettings().setBuiltInZoomControls(false);
        // 设置不可以缩放
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setDisplayZoomControls(false);
        // 设置的WebView是否支持变焦
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setBuiltInZoomControls(false);
        webview.getSettings().setUseWideViewPort(false);
        //自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        // 自适应 屏幕大小界面
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                int w = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                int h = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                // 重新测量
                webview.measure(w, h);
            }
        });
    }

    @Override
    public void initListener() {
        comment_check.setOnClickListener(this);
        comment_layout.setOnClickListener(this);
        buy_now.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        title_img.setOnClickListener(this);
        right_imageview.setOnClickListener(this);
        //主要用于监听上下滑动页面当前页面时第几页
        ptlm.showCurrentPosition(new PullUpToLoadMore.CurrentPositionLisener() {
            @Override
            public void currentPosition(int position) {
                Log.e("======postiton", position + "");
                if (1 == position) {
                    title_layout_first.setVisibility(View.GONE);
                }
                if (0 == position) {
                    title_layout_first.setVisibility(View.VISIBLE);
                }
            }
        });
        //title按钮在webview页面时返回点击事件执行监听
        title_llBack.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (canGoBack()) {
                    goBack();
                } else {
                    SuiteProductsDetailActivity.this.finish();
                }
            }
        });
    }

    @Override
    public void loadData() {
        getGoodsDetails(good_id);
        getCommentList(1, good_id);
        webview.loadUrl(ur + good_id);
    }

    private void getCommentList(int page_num, String goods_id) {
        ProductsCommentApi api = new ProductsCommentApi(page_num, goods_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<CommentListResp>>() {
            @Override
            public void onNext(HttpResp<CommentListResp> resp) {
                if (null != resp) {
                    if (2 < resp.data.getCOMMENT_LIST().size()) {
                        mList.add(resp.data.getCOMMENT_LIST().get(0));
                        mList.add(resp.data.getCOMMENT_LIST().get(1));
                    } else {
                        mList.addAll(resp.data.getCOMMENT_LIST());
                    }
                    sum_comment.setText(resp.data.getCOMMENT_NUM() + "条评论");
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    //设置recyclerview
    private void initRecylerView() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView mRecyclerView, int dx, int dy) {
                super.onScrolled(mRecyclerView, dx, dy);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.comment_check:
                Intent intentcomment_check = new Intent(this, CommentListActivity.class);
                intentcomment_check.putExtra("good_id", good_id);
                startActivity(intentcomment_check);
                break;
            case R.id.comment_layout:
                Intent intent_comment_layout = new Intent(this, CommentListActivity.class);
                intent_comment_layout.putExtra("good_id", good_id);
                startActivity(intent_comment_layout);
                break;
            case R.id.back_layout:
                SuiteProductsDetailActivity.this.finish();
                break;
            case R.id.right_imageview://右上角分享
                share();
                break;
            case R.id.buy_now:
                if (AppUtil.isLogin()) {
                    if (GoodType.DEVICE.equals(data.getGOODS_TYPE())) {
                        ToastUtil.showToast(SuiteProductsDetailActivity.this, "该类型产品暂不能购买");
                    } else {
                        Intent intent = new Intent(this, SubmitPersonInfoActivity.class);
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_SALE_PRICE, data.getGOODS_SALE_MONEY());
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_SALE_TYPE, data.getSALE_TYPE());
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_PRICE, data.getGOODS_MONEY());
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_GOOD_TYPE, data.getGOODS_TYPE());
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_GOODS_NAME, data.getGOODS_NAME());
                        intent.putExtra(SubmitPersonInfoActivity.EXTRA_GOODS_PIC, data.getGOODS_PIC());
                        startActivity(intent);
                    }
                } else {
                    AppUtil.startLoginActivity(mContext);
                }
                break;
            case R.id.title_img://状态栏右上角分享
                share();
                break;
        }
    }

    //友盟分享的方法
    private void share() {
        try {
            UMImage umImage = new UMImage(SuiteProductsDetailActivity.this, data.getGOODS_PIC());
            new ShareAction(SuiteProductsDetailActivity.this).withText(data.getGOODS_DESC()).withTitle(data.getGOODS_NAME()).withMedia(umImage).withTargetUrl(shareurl + good_id).setDisplayList(SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN).setCallback(umShareListener).open();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    //获取当前商品详情方法
    private void getGoodsDetails(final String goods_id) {
        GetGoodsDetailApi api = new GetGoodsDetailApi(goods_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp<GoodsDetailResp>>() {
            @Override
            public void onNext(HttpResp<GoodsDetailResp> resp) {
                if (null != resp.data) {
                    SuiteProductsDetailActivity.this.data = resp.data;
                    //goods_type商品类别 1健康套装系列 2重疾卡系列 3HMO卡系列
                    if (resp.data.getGOODS_TYPE().equals("1")) {
                        suit_content_layout.setVisibility(View.VISIBLE);
                    } else {
                        suit_content_layout.setVisibility(View.GONE);
                    }
                    setData(resp.data);
                }
            }
        });
    }

    /**
     * 处理顶部的viewpager界面数据
     *
     * @param data
     */
    private void dealTopViewPager(GoodsDetailResp data) {
        //这里我们先创建一个图片网络地址的集合,页面顶部轮滑图
        List<String> imgurl_list = new ArrayList<String>();
        for (int i = 0; i < data.getPIC_INFO().size(); i++) {
            imgurl_list.add(data.getPIC_INFO().get(i).getPIC_ADD());
        }
        List<ImageView> listimg = new ArrayList<ImageView>();
        //因为数量小于三个的时候会出现白屏,所以1张的时候凑够三张图片,两张的时候翻一倍
        if (imgurl_list.size() == 1) {
            for (int j = 0; j < 3; j++) {
                for (int i = 0; i < imgurl_list.size(); i++) {
                    ImageView imageView = new ImageView(this);
                    //设置加载下的图片宽度
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(this).load(imgurl_list.get(i))
                            .error(R.drawable.logo)
                            .into(imageView);
                    listimg.add(imageView);
                }
            }
        }
        if (imgurl_list.size() == 2) {
            for (int j = 0; j < 2; j++) {
                for (int i = 0; i < imgurl_list.size(); i++) {
                    ImageView imageView = new ImageView(this);
                    //设置加载下的图片宽度
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(this).load(imgurl_list.get(i))
                            .error(R.drawable.order_confirm_product_default)
                            .into(imageView);
                    listimg.add(imageView);
                }
            }
        } else {
            for (int i = 0; i < imgurl_list.size(); i++) {
                ImageView imageView = new ImageView(this);
                //设置加载下的图片宽度
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                Glide.with(this).load(imgurl_list.get(i))
                        .error(R.drawable.order_confirm_product_default)
                        .into(imageView);
                listimg.add(imageView);
            }
        }

        if (0 < listimg.size()) {
            viewpager.setAdapter(new SuitPagerAdapter(listimg));
            //设置每次加载时第一页在MAX_VALUE / 2 - Extra 页，造成用户无限轮播的错觉
            int startPage = Short.MAX_VALUE / 2;
            int extra = startPage % listimg.size();
            startPage = startPage - extra;
            if (from == 1) {
                //此从精品推荐页面跳转过来的,然后设置当前页面应该显示第几个
                viewpager.setCurrentItem(startPage + position);
            } else {
                viewpager.setCurrentItem(startPage);
            }
//            viewpager.setCurrentItem(0);
        }
        //设置小圆点
        setdot(imgurl_list);
    }

    /**
     * 设置顶部viewpager页面上小圆点
     *
     * @param imgurl_list
     */
    private void setdot(final List<String> imgurl_list) {
        int wrop = RadioGroup.LayoutParams.WRAP_CONTENT;
        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(wrop, wrop);
        params.leftMargin = 15;
        for (int i = 0; i < imgurl_list.size(); i++) {
            RadioButton button = new RadioButton(this);
            button.setEnabled(false);
            button.setId(i);
            button.setButtonDrawable(R.drawable.dot_selector);
            if (i == 0) {
                pager_radiogroup.addView(button);
            } else {
                pager_radiogroup.addView(button, params);
            }
        }
        if (from == 1) {
            //如果是从精品推荐页面过来的,依据精品推荐页面滑动页面位置的当前第几个图片位置同样设置
            pager_radiogroup.check(0 + position);
        } else {
            pager_radiogroup.check(0);
        }
        viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                pager_radiogroup.check(arg0 % imgurl_list.size());
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    // 利用handler改变viewpager页面顶部的滑动图片
    public void pagercirculation() {
        handler.sendEmptyMessageDelayed(0, 3000);
    }

    //友盟分享的监听
    UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.e("====plat", "platform" + platform);
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t != null) {
                XHLog.d("throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };


    //--------------下滑的底部是一个webview,解决返回按钮事件冲突问题
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        SuiteProductsDetailActivity.this.finish();
        return false;

    }

    public boolean canGoBack() {
        return webview != null && webview.canGoBack();
    }

    public void goBack() {
        if (webview != null) {
            webview.goBack();
        }
    }

}
